package com.liangyu.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class FileUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);
    private String origName;

    private String oldName;

    private String realName ;

    private Long  fileSize;

    private String suffix ;

    public String getOldName() {
        return oldName;
    }

    public static final String FILE_SUFFIX = "xlsx,xls,png,jpg,jpeg,docx,doc,pdf,txt,zip,rar,ppt,pptx,html,htm";

    public String getOrigName() {
        return origName;
    }

    public void setOrigName(String origName) {
        this.origName = origName;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

    public Long getFileSize() {
        return fileSize;
    }

    public void setFileSize(Long fileSize) {
        this.fileSize = fileSize;
    }

    public String getSuffix() {
        return suffix;
    }

    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }

    public String uploadImage(HttpServletRequest request, String path_deposit, MultipartFile file, boolean isRandomName) {

        //上传
        try {
            String[] typeImg= FILE_SUFFIX.split(",");

            if(file!=null){
                this.origName=file.getOriginalFilename();// 文件原名称
                //获取文件大小
                this.fileSize = file.getSize();
                //文件大小向上取整
//                           fileSize = new Double(Math.ceil(new Double(file.getSize())/1024)).longValue();
                // 判断文件类型
                String type=origName.indexOf(".")!=-1?origName.substring(origName.lastIndexOf(".")+1, origName.length()):null;
                this.suffix = type ;
                if (type!=null) {
                    boolean booIsType=false;
                    for (int i = 0; i < typeImg.length; i++) {
                        if (typeImg[i].equals(type.toLowerCase())) {
                            booIsType=true;
                        }
                    }
                    //类型正确
                    if (booIsType) {
                        //存放图片文件的路径
                        String fileSrc = path_deposit;

                        String dateStr = formateString(new Date());

                        realName = dateStr+"."+type;
                        //判断是否存在目录
                        File targetFile=new File(fileSrc,realName);
                        if(!targetFile.exists()){
                            targetFile.getParentFile().mkdirs();//创建目录
                        }
                        //上传
                        file.transferTo(targetFile);
                        //完整路径
                        LOGGER.info("完整路径:"+targetFile.getAbsolutePath());
                        return fileSrc;
                    }
                }
            }
            return null;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 生成“yyyyMMddHHmmss+时间戳后三位”的字符串
     * @param date
     * @return
     */
    public String formateString(Date date){
        SimpleDateFormat dateFormater = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr = dateFormater.format(date);
        String timeMillis = System.currentTimeMillis()+ "";
        String result = dateStr + timeMillis.substring(timeMillis.length()-3);
        /*String list[] = dateFormater.format(date).split("-");
        String result = "";
        for (int i=0;i<list.length;i++) {
            result += list[i];
        }*/
        return result;
    }

    /**
     * 根据文件的名称来获取文件的类型（后缀名）
     * @param file
     * @return
     */
    public static String getFileTypeByFileName(MultipartFile file){
        String origName=file.getOriginalFilename();// 文件原名称
        // 判断文件类型
        String type=origName.indexOf(".")!=-1?origName.substring(origName.lastIndexOf(".")+1, origName.length()):null;
        return type ;
    }


    /**
     * 判断文件是否是允许上传的类型（目前允许的类型不是通过参数获取，需优化）
     * @param file
     * @return
     */
    public static boolean isAllowFileType(MultipartFile file){
        boolean isAllow = false ;
        if(file!=null){
            String fileSuffix = getFileTypeByFileName(file);
            //判断是否是允许上传的类型
            if(fileSuffix!=null&&!"".equals(fileSuffix)){
                //将大写统一改为小写
                fileSuffix = fileSuffix.toLowerCase();
                String[] suffixArray = FILE_SUFFIX.split(",");
                for (String type:suffixArray) {
                    if(fileSuffix.equals(type)){
                        isAllow = true ;
                        break;
                    }
                }
            }
        }
        return isAllow ;
    }


    public String uploadImg(HttpServletRequest request, String path_deposit, MultipartFile file, boolean isRandomName) {

        //上传
        try {
            String[] typeImg= FILE_SUFFIX.split(",");

            if(file!=null){
                origName=file.getOriginalFilename();// 文件原名称
//
                //获取文件大小
                fileSize = file.getSize();
                // 判断文件类型
                String type=origName.indexOf(".")!=-1?origName.substring(origName.lastIndexOf(".")+1, origName.length()).toLowerCase():null;
                if (type!=null) {
                    boolean booIsType=false;
                    for (int i = 0; i < typeImg.length; i++) {
                        if (typeImg[i].equals(type.toLowerCase())) {
                            booIsType=true;
                        }
                    }
                    //类型正确
                    if (booIsType) {
                        //存放图片文件的路径
                        String fileSrc = path_deposit;

                        String dateStr = getDateAndTimeMillis();
                        oldName = origName;
                        origName= origName.substring(origName.lastIndexOf("."));
                        origName= new Date().getTime()+origName;
                        origName = dateStr+"."+type;

                        //判断是否存在目录
                        File targetFile=new File(fileSrc,origName);
                        if(!targetFile.exists()){
                            targetFile.getParentFile().mkdirs();//创建目录
                        }
                        //上传
                        file.transferTo(targetFile);
                        //完整路径
                        LOGGER.info("完整路径:"+targetFile.getAbsolutePath());
                        return fileSrc;
                    }
                }
            }
            return null;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 生成“yyyyMMddHHmmss+时间戳后三位”的字符串
     * @param
     * @return
     */
    public String getDateAndTimeMillis(){
        SimpleDateFormat dateFormater = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr = dateFormater.format(new Date());
        String timeMillis = System.currentTimeMillis()+ "";
        String result = dateStr + timeMillis.substring(timeMillis.length()-3);
        return result;
    }
    /**
     * 解析html文件
     * @param file
     * @return
     */
    public static String getHtmlBody(File file) throws IOException {
        String body = "";
        FileInputStream iStream = new FileInputStream(file);
        Reader reader = new InputStreamReader(iStream);
        BufferedReader htmlReader = new BufferedReader(reader);

        String line;
        boolean found = false;
        while (!found && (line = htmlReader.readLine()) != null) {
            if (line.toLowerCase().indexOf("<body") != -1) { // 在<body>的前面可能存在空格
                found = true;
            }
        }

        found = false;
        while (!found && (line = htmlReader.readLine()) != null) {
            if (line.toLowerCase().indexOf("</body") != -1) {
                found = true;
            } else {
                // 如果存在图片，则将相对路径转换为绝对路径
                String lowerCaseLine = line.toLowerCase();
                if (lowerCaseLine.contains("src")) {

                    //这里是定义图片的访问路径
                    String directory = "D:/test";
                    // 如果路径名不以反斜杠结尾，则手动添加反斜杠
                    /*if (!directory.endsWith("\\")) {
                        directory = directory + "\\";
                    }*/
                    //    line = line.substring(0,  lowerCaseLine.indexOf("src") + 5) + directory + line.substring(lowerCaseLine.indexOf("src") + 5);
                    /*String filename = extractFilename(line);
                    line = line.substring(0,  lowerCaseLine.indexOf("src") + 5) + directory + filename + line.substring(line.indexOf(filename) + filename.length());
                */
                    // 如果该行存在多个<img>元素，则分行进行替代
                    String[] splitLines = line.split("<img\\s+"); // <img后带一个或多个空格
                    // 因为java中引用的问题不能使用for each
                    for (int i = 0; i < splitLines.length; i++) {
                        if (splitLines[i].toLowerCase().startsWith("src")) {
                            splitLines[i] = splitLines[i].substring(0, splitLines[i].toLowerCase().indexOf("src") + 5)
                                    + directory
                                    + splitLines[i].substring(splitLines[i].toLowerCase().indexOf("src") + 5);
                        }
                    }

                    // 最后进行拼接
                    line = "";
                    for (int i = 0; i < splitLines.length - 1; i++) { // 循环次数要-1，因为最后一个字符串后不需要添加<img
                        line = line + splitLines[i] + "<img ";
                    }
                    line = line + splitLines[splitLines.length - 1];
                }

                body = body + line + "\n";
            }
        }
        htmlReader.close();
        //        System.out.println(body);
        return body;
    }

    /**
     * 文件化为字节流
     * @param file
     * @return
     * @throws IOException
     */
    public static byte[] getBytes(File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream b = new ByteArrayOutputStream(fis.available());
        byte[] bytes = new byte[fis.available()];
        int temp;
        while ((temp = fis.read(bytes)) != -1) {
            b.write(bytes, 0, temp);
        }
        fis.close();
        b.close();
        return b.toByteArray();
    }
}
